function initialize() {
	$('req').addEvent('keyup', onSearchKeyUp);
}

function onSearchKeyUp() {
	var req = $('req').value;	
	getTmatics(req);
}

function getTmatics(req, semecode) {
	$('loading').setStyle('display', 'inline');
	new Request.JSONP({
	  url: 'http://www.t-ma-tic.com/factory/getP',
	    data: {
	        q: req,
	        s: semecode
	    },
	    onComplete: function(tmatics) {
	    	//To see the result of the JSONP requests
	    	//$('log').innerHTML += "<p>" + JSON.encode(tmatics) + "</p>";
	    	getTmaticsHandler(tmatics)
	    }
	}).send();
}

function renderInjectTmatic(tmatic, semecode, class) {
	
	var el = new Element('div', {'class' : class, 'html' : tmatic, 'events' : {'click' : function(){ getTmatics('',this.semecode); } }}); 				
	el.tmatic = tmatic;
	el.semecode = semecode;
	
	return el;	
}

function getTmaticsHandler(tmatics) {
	
	var div = new Element('div', {'class' : 'inner','styles' : {'padding' : '10px'}});

	for(y=0 ; y<tmatics['tmatics'].length; y++)
	{
		renderInjectTmatic(tmatics['tmatics'][y]['title'], tmatics['tmatics'][y]['semecode'],'current' ).inject(div);
		
		if(tmatics['tmatics'][y]['similar']) 
		{
			for(var x=0 ; x< tmatics['tmatics'][y]['similar'].length; x++) 
			{
				renderInjectTmatic(tmatics['tmatics'][y]['similar'][x]['title'], tmatics['tmatics'][y]['similar'][x]['semecode'], 'similar').inject(div);
			}
		}

		if(tmatics['tmatics'][y]['linked']) 
		{
			for(var x=0 ; x< tmatics['tmatics'][y]['linked'].length; x++) 
			{
				renderInjectTmatic(tmatics['tmatics'][y]['linked'][x]['title'], tmatics['tmatics'][y]['linked'][x]['semecode'], 'linked').inject(div);
			}
		}
	}
	
	$('searchResults').innerHTML = '';	
	div.inject($('searchResults'));
	
	$('loading').setStyle('display', 'none');
}
